import { InjectQueue } from "@nestjs/bullmq";
import { Injectable, OnModuleInit } from "@nestjs/common";
import { Cron, CronExpression } from "@nestjs/schedule";
import { InjectDataSource } from "@nestjs/typeorm";
import { Queue } from "bullmq";
import dayjs from "dayjs";
import { DataSource } from "typeorm";
import { DatabaseName } from "@/database/database.enum";

@Injectable()
export class SysLogService implements OnModuleInit {
    constructor(
        @InjectDataSource(DatabaseName.LOGS) private readonly dataSource: DataSource,
        @InjectQueue("sysLogToEsQueue") private readonly sysLogToEsQueue: Queue,
    ) {}

    async onModuleInit(): Promise<void> {
        // 应用启动时创建日志表, 防止漏建
        await this.createLogsTable(false);
        await this.createLogsTable(true);
    }

    /** 自动创建下个月的日志表 */
    @Cron(CronExpression.EVERY_1ST_DAY_OF_MONTH_AT_NOON)
    async createLogsTable(isNextMonth: boolean = true) {
        const nextMonth = isNextMonth ? dayjs().add(1, "month").format("YYYYMM") : dayjs().format("YYYYMM");
        const newTableName = `sys_operation_log_${nextMonth}`;
        const templateTable = `sys_operation_log_template`;

        const exist = await this.dataSource.query(`SELECT to_regclass('${newTableName}') AS table_exists;`);

        if (!exist[0].table_exists) {
            await this.dataSource.query(`CREATE TABLE ${newTableName} (LIKE ${templateTable} INCLUDING ALL);`);
        }
    }

    // 每分钟执行一次同步
    @Cron(CronExpression.EVERY_MINUTE)
    async syncLogsToEs() {
        this.sysLogToEsQueue.add("syncLogsToEs", {});
    }
}
